import pandas as pd
from DatetimeUtils import choose_day
from ListUtils import anti_join
import time
"""
大盘指数每日指标
"""
# 指数列表
index_basic = ['000001.SH', '000300.SH','000905.SH','399001.SZ','399005.SZ','399006.SZ','399016.SZ','399300.SZ','000005.SH','000006.SH','000016.SH']

def deal_append(query_start_, query_end_, engine, pro, index_name):
    """
    通过anti_join函数处理增量数据
    """
    source_list_ = pro.index_dailybasic(ts_code=index_name, start_date=query_start_, end_date=query_end_)
    if len(source_list_) > 0:
        sql_ = 'select b.ts_code, b.trade_date from index_dailybasic b WHERE b.ts_code = "' + index_name + '" and b.trade_date >= ' + query_start_ + ' and b.trade_date <= ' + query_end_
        target_list_ = pd.read_sql(sql_, engine)
        # print('index_dailybasic：(%s)' % target_list_)
        if len(target_list_) == 0:
            source_list_.to_sql('index_dailybasic', con=engine, index=False, index_label=['ts_code', 'trade_date'], if_exists='append')
            print('数据库内未找到数据则全部添加：(%s)' % source_list_)
        else:
            # 数据库内有历史数据则增量添加
            source_list_ = anti_join(source_list_, target_list_, ['ts_code', 'trade_date'])
            if len(source_list_) > 0:
                print('增量：(%s)' % source_list_)
                source_list_.to_sql('index_dailybasic', con=engine, index=False, index_label=['ts_code', 'trade_date'], if_exists='append')
    time.sleep(2)




def insert_history_data_index_daily_basic(engine, pro):
    """
    是否查询并保存历史数据
    """
    insert_history_data_flag = True
    if insert_history_data_flag:
        current_year = choose_day(0).strftime('%Y')
        start_year = 2004  # 起始 2004
        """
        处理历史数据
        """
        for j in range(0, len(index_basic)):
            for i in range(start_year, int(current_year)):
                query_start = '%d' % i + '0101'  # 查询开始
                query_end = '%d' % i + '1231'  # 查询结束
                deal_append(query_start, query_end, engine, pro, index_basic[j])

            """
            处理当年数据
            """
            current_day = choose_day(0).strftime('%Y%m%d')
            year_first_day = current_year + '0101'
            deal_append(year_first_day, current_day, engine, pro, index_basic[j])


def update_current_data_index_daily_basic(engine_, pro_):
    """
    更新当前数据，后续使用定时器
    """
    insert_current_flag = True
    if insert_current_flag:
        for j in range(0, len(index_basic)):
            day_updates = 30 #设定更新30天数据
            current_day = choose_day(0).strftime('%Y%m%d')
            that_day = choose_day(day_updates).strftime('%Y%m%d')
            deal_append(that_day, current_day, engine_, pro_, index_basic[j])